<?php
namespace control;
/*
*报价单类
*/

class quotationsClass extends adIndexClass
{
	private const page    = 'quotations';
	private const table   = 'quotations';
	private const tableMx = 'quotations_detail';
	private const title   = '报价单';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'clientQuoSearch':
                $tr = [
                    'orderNo'          => [
                        'name'  => "{l.quotations.clientQuoSearch.orderNo}",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'description' => [
                        'name'  => "{l.quotations.clientQuoSearch.description}",
                        'width' => 300,
                    ],
                    'manager'  => [
                        'name'  => '{l.quotations.clientQuoSearch.manager}',
                        'width' => 200,
                    ],
                    'money'         => [
                        'name'  => '{l.quotations.clientQuoSearch.money}（' . static::$unit . '）',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'recordDate'          => [
                        'name'  => '{l.quotations.clientQuoSearch.recordDate}',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '{l.quotations.clientQuoSearch.state}',
                        'width' => 150,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "{l.quotations.clientQuoSearch.orderNo}",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'description' => [
                        'name'  => "{l.quotations.clientQuoSearch.description}",
                        'width' => 300,
                    ],
                    'companyName' => [
                        'name'  => "{l.quotations.clientQuoSearch.khid}",
                        'width' => 300,
                    ],
                    'manager'  => [
                        'name'  => '{l.quotations.clientQuoSearch.manager}',
                        'width' => 150,
                    ],
                    'money'         => [
                        'name'  => '{l.quotations.clientQuoSearch.money}（' . static::$unit . '）',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'recordDate'          => [
                        'name'  => '{l.quotations.clientQuoSearch.recordDate}',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '{l.quotations.clientQuoSearch.state}',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function clientQuoOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('quotations.clientQuo.orderNo') => text(array("name" => "orderNo")).
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    L('quotations.clientQuoSearch.description')   => text(array("name" => "description")),
                    L('quotations.clientQuo.stid') => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                ],
                [
                    L('quotations.clientQuo.createTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 客户页卡报价单
	 *
	 * @return bool|string
	 */
	public function clientQuo(): bool|string
	{
        $khid = $this->get('id');
        $html = $this->clientQuoOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('quotations.clientQuoSearch.detail') . "','" . $url . "&fun=edit&khid={$khid}')\" class='spanButton'>".L('quotations.clientQuoSearch.new')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('quotations.clientQuoSearch.del')."</span>\n";
        }
		$json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
		return json_encode($json, 320);
	}

	public function clientQuoSearch(): bool|string
	{
		$khid = $this->post('targetId');
		//like查询数组
		$like = array(
			"orderNo"  => $this->post('orderNo'),//证件编号
            "description" => $this->post('description'),
		);
		//全等查询数组
		$equal = array(
			"state" => $this->post('state'),
			"stid"  => $this->post('stid'),
            'coid'=>self::$coid
		);
		$and   = " and khid = '$khid'";
		if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where                         = search(array("like" => $like, "=" => $equal)) . $and;
		$_SESSION[self::page]['where'] = $where;
		$page                          = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("quoForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"edit"   => array("title" => L('quotations.clientQuoSearch.edit'), "click" => "newIframe('" . L('quotations.clientQuoSearch.detail') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
				"detail" => array("title" => L('quotations.clientQuoSearch.detail'), "click" => "newIframe('" . L('quotations.clientQuoSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "money":
                        $row[] = self::lostZero($array['money'], 'amount');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='quoForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('quotations.clientQuoSearch.orderNo') => text(array("name" => "orderNo")),
                    L('quotations.clientQuoSearch.description')   => text(array("name" => "description")),
                    L('quotations.clientQuoSearch.khid') => clientClass::kehuSelect(array('name' => 'khid')),
                ],
                [
                    L('quotations.clientQuoSearch.manager')  => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                    L('quotations.clientQuoSearch.recordDate') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    L('quotations.clientQuoSearch.state') => select(["name" => "state", 'option' => ['制单', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('quotations.clientQuoSearch.detail') . "','" . $url . "&fun=edit')\" class='spanButton'>".L('quotations.clientQuoSearch.new')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('quotations.clientQuoSearch.del')."</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>".L('quotations.clientQuoSearch.batchPrint')."</span>\n";
        }
		//返回
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//like查询数组
		$like = array(
			"orderNo" => $this->post('orderNo'),//证件编号
			"description" => $this->post('description'),
		);
		//全等查询数组
		$equal = array(
			"state" => $this->post('state'),
			"stid"  => $this->post('stid'),
			"khid"  => $this->post('khid'),
            'coid'=>self::$coid
		);
		$and   = '';
		if ($this->post('createTime')) {
			$and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
		}
		// 查看自己
		if (!$this->power(self::page, 'seeAll')) {
			$and .= " and (manager = '" . self::$stid . "' or stid = '" . self::$stid . "') ";
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where                         = search(array("like" => $like, "=" => $equal)) . $and;
		$_SESSION[self::page]['where'] = $where;
		$page                          = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"edit"   => array("title" => L('quotations.clientQuoSearch.edit'), "click" => "newIframe('" . L('quotations.clientQuoSearch.detail') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
				"detail" => array("title" => L('quotations.clientQuoSearch.detail'), "click" => "newIframe('" . L('quotations.clientQuoSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
				'print'  => array('title' => L('quotations.clientQuoSearch.print'), 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
			);
			if ($array['state'] != '制单') {
				unset($dominate['edit']);
			}
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "companyName":
                        $kehu = query('kehu', "khid = '$array[khid]'");
                        $row[] = $kehu['companyName'];
                        break;
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "money":
                        $row[] = self::lostZero($array['money']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalMoney = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'      => self::lostZero($totalMoney['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = "<form name='listForm'>" .$li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id   = $this->get('id') ?: self::getId();
		$info = query(self::table, " id = '" . $id . "' ");

		$button[]    = [
			"name"  => '保存为草稿',
			"type"  => "点击事件",
			"title" => '保存为草稿',
			'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		];
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
		$tr[]        = ['', '{l.quotations.edit.code}', '{l.quotations.edit.name}', '{l.quotations.edit.model}', '{l.quotations.edit.unit}', '{l.quotations.edit.num}', '{l.quotations.edit.price}(' . static::$unit . ')', '{l.quotations.edit.money}（' . static::$unit . '）', ' {l.quotations.edit.rate}%', '{l.quotations.edit.taxMoney}（' . static::$unit . '）', '{l.quotations.edit.moneyWithTax}（' . static::$unit . '）', '{l.quotations.edit.mxText}'];
		$opportunity = [];
        $totalArr = ['total_num'=>0,'total_row_money'=>0,'total_tax_money'=>0,'total_money'=>0];
		if ($this->get('opId')) {
			$opportunity = query('opportunity', "id = '{$this->get('opId')}'");
			$products    = array_filter(explode(',', $opportunity['products']));
			if (is_array($products)) {
				foreach ($products as $k=>$mid) {
					$material = query('material', " id = '$mid'");
					$mxId     = self::getId();
					$tr[]     = [
                        componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                        hidden(array('name' => 'mxId[]', 'value' => $mxId)) .
                        hidden(array('name' => 'materialId[]', 'value' => $material['id'])),
						$material['code'],
                        $material['name'],
                        $material['model'],
						select(array(
						    'name' => 'unitDetail[]',
                            'data' => ['unit' => $material['unit']],
                            'value' => $material['unit'],
                            'option' => machiningOrderClass::unitOption($material['id'])
                        )),
						text(array('name' => 'num[]', 'blur' => "countMoney", 'other' => self::digitalFiltering('numPrecision'), 'value' => '')),
						text(array('name' => 'price[]', 'blur' => "countMoney", 'other' => self::digitalFiltering('pricePrecision'), 'value' => '')),
						"<span class='rowMoney'></span>",
						select(array('name' => 'rate[]', 'title' => L('quotations.edit.rate'), 'option' => explode('，', para('taxRate')), 'value' => '')),
						"<span class='taxMoney'></span>",
						text(array('name' => 'moneyWithTax[]', 'type' => 'text', 'blur' => 'calculatePrice', 'other' => self::digitalFiltering())),
						text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => '')),
					];
				}
			}
		} else {
			$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
			foreach ($result['array'] as $k=>$array) {
				$material = query('material', " id = '$array[materialId]'");
				$tr[]     = [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                    hidden(array('name' => 'materialId[]', 'value' => $material['id'])),
					$material['code'],
                    $material['name'],
                    $material['model'],
					select(array(
					    'name' => 'unitDetail[]',
                        'data' => ['unit' => $material['unit']],
                        'value' => $material['unit'],
                        'option' => machiningOrderClass::unitOption($material['id'])
                    )),
					text(array('name' => 'num[]', 'blur' => "countMoney", 'other' => self::digitalFiltering('numPrecision'), 'value' => $array['num'] ? self::lostZero($array['num'], 'numPrecision') : '')),
					text(array('name' => 'price[]', 'blur' => "countMoney", 'other' => self::digitalFiltering('pricePrecision'), 'value' => $array['price'] ? self::lostZero($array['price'], 'pricePrecision') : '')),
					"<span class='rowMoney'>" . ($array['moneyWithOutTax'] ? self::lostZero($array['moneyWithOutTax'], 'pricePrecision') : '') . "</span>",
					select(array('name' => 'rate[]', 'change' => "countMoney", 'title' => L('quotations.edit.rate'), 'option' => explode('，', para('taxRate')), 'value' => $array['taxRate'] * 100)),
					"<span class='taxMoney'>".self::lostZero($array['taxMoney'])."</span>",
					text(array('name' => 'moneyWithTax[]', 'type' => 'text', 'blur' => 'calculatePrice', 'other' => self::digitalFiltering(), 'value' => $array['money'] ? self::lostZero($array['money']) : '')),
					text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['text'])),
				];
                $totalArr['total_num'] += $array['num'];
                $totalArr['total_row_money'] += $array['moneyWithOutTax'];
                $totalArr['total_tax_money'] += $array['taxMoney'];
                $totalArr['total_money'] += $array['money'];
			}
		}
        $total = [
            5 => "<span id='total_num'>".self::lostZero($totalArr['total_num'])."</span>",
            7 => "<span id='total_row_money'>".self::lostZero($totalArr['total_row_money'])."</span>",
            9 => "<span id='total_tax_money'>".self::lostZero($totalArr['total_tax_money'])."</span>",
            10 => "<span id='total_money'>".self::lostZero($totalArr['total_money'])."</span>",
        ];
		$list  = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
		$selectProductWord = L('quotations.edit.selectProduct');

		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . L('quotations.edit.description')."：" => text(["name" => "description", 'class' => 'text', "value" => $info['description']]),
                    L('quotations.edit.opId')."："      => selectMultiple(["name" => "opId", "value" => $this->get('opId') ?: $info['opId'], 'table' => "opportunity",'where'=>"coid = '".self::$coid."'", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('quotations.edit.choice')]),
                    must . L('quotations.edit.khid')."："       => clientClass::kehuSelect(array('value' => $this->get('khid') ?: ($opportunity['khid'] ?? $info['khid']))),
                    must . L('quotations.edit.recordDate')."：" => text(["name" => "recordDate", 'class' => 'text', 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                ],
                [

                    must . L('quotations.edit.startDate')."：" => text(["name" => "startDate", 'class' => 'text', 'laydate' => [], "value" => $info['startDate']]),
                    L('quotations.edit.endDate')."："        => text(["name" => "endDate", 'class' => 'text', 'laydate' => [], "value" => $info['endDate']]),
                ],
                [
                    L('quotations.edit.mxText')."：" => textarea(["name" => "text", 'class' => 'text', "value" => $info['text']]),
                ],
            ]
        ]);
        $checked    = $info['isTax'] ? 'checked' : '';
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => L('quotations.edit.quotationsMx'),
            'button' => "<span class=\"smallButton\" onclick=\"layer('{$this->get('cla')}','addMx',$('form[name=quotationsEditForm]').serialize())\">{$selectProductWord}</span>
<span style='margin-left: 20px;'><label class='checkbox' title='单价是否含税'><input name='isTax' onclick=\"taxChange(this)\" type='checkbox' $checked value='1'><span></span>&nbsp;含税</label></span>",
            'html' => $list,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
		]);
		$choiceUnitWord = L('quotations.edit.choiceUnit');
		$data['html'] .= <<<efo
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
    },'json');
}
//根据单位转换所需数量和库存
function unitChange(e){
    let unit = e.value;
    if (!unit){
        msg('{$choiceUnitWord}')
        return '';
    }
    let oldUnit = $(e).data('unit');
    $(e).data('unit',unit);
    let num = $(e).parent().parent().find("[name='num[]']").val();
    let id = $(e).parent().parent().find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla=machiningInOrder&fun=unitChange',{unit:unit,oldUnit:oldUnit,num:num,id:id},function(res) {
        if (res.warn==2){
            $(e).parent().parent().find("[name='num[]']").val(res.num);
            countMoney(e);
        }else{
            msg(res.warn);
        }
    },'json');
}

//通过单价计算金额，税额等
function countMoney(e){
    let trObj = $(e).parent().parent();
    countProcess(trObj)
}
function countProcess(trObj){
    let price = trObj.find("[name='price[]']").val();
    let num = trObj.find("[name='num[]']").val();
    let rate = trObj.find("[name='rate[]']").val();
    rate = Number(rate)/100;
    let money;
    let taxMoney,moneyWithTax;
    if($("[name='isTax']").is(":checked")){
       //含税单价
       taxMoney = (Number(price)*Number(num)/(1+rate)*rate).toFixed(amountPrecision);
       moneyWithTax = (Number(price)*Number(num)).toFixed(amountPrecision);
       money = Number(moneyWithTax-taxMoney).toFixed(amountPrecision)
    }else{
       //未含税单价
        taxMoney = (Number(price)*Number(num)*rate).toFixed(amountPrecision);
        moneyWithTax = (Number(price)*Number(num)*(1+rate)).toFixed(amountPrecision);
        money = (Number(price)*Number(num)).toFixed(amountPrecision);
    }
    trObj.find(".rowMoney").html(money)
    trObj.find(".taxMoney").html(taxMoney)
    trObj.find("[name='moneyWithTax[]']").val(moneyWithTax)
    calculateTotal()
}


//通过价税合计计算单价
function calculatePrice(e){
    let trObj = $(e).parent().parent();
    let moneyWithTax = e.value;//价税合计
    let num = trObj.find("[name='num[]']").val();
    let rate = trObj.find("[name='rate[]']").val();
    if(num > 0){
        rate = Number(rate)/100;
        let taxMoney,price,money;
        taxMoney = (moneyWithTax/(1+rate)*rate).toFixed(amountPrecision);//税额
        if($("[name='isTax']").is(":checked")){
           //含税
           price = moneyWithTax/num;
           money = moneyWithTax-taxMoney;
        }else{
           //未含税
            price = (moneyWithTax-taxMoney)/num;
            money = moneyWithTax-taxMoney;
        }
        trObj.find(".rowMoney").html(money.toFixed(amountPrecision))
        trObj.find(".taxMoney").html(taxMoney)
        trObj.find("[name='price[]']").val(price.toFixed(publicSettings.pricePrecision.num))
    }
    calculateTotal()
}

//计算总金额，总税额
function calculateTotal(table=''){
    table = table ? table : $('.editList')
    let num = 0,
    rowMoney = 0,
    taxMoney = 0,
    money = 0;
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var rowMoneyText = table.find(".rowMoney").eq(index).text()
        if(rowMoneyText){
            rowMoney+=Number(rowMoneyText);
        }
        var taxMoneyText = table.find(".taxMoney").eq(index).text()
        if(taxMoneyText){
            taxMoney+=Number(taxMoneyText);
        }
        var moneyValue = table.find("[name='moneyWithTax[]']").eq(index).val()
        if(moneyValue){
            money+=Number(moneyValue);
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
    $("#total_row_money").text(rowMoney.toFixed(amountPrecision));
    $("#total_tax_money").text(taxMoney.toFixed(amountPrecision));
    $("#total_money").text(money.toFixed(amountPrecision));
}
//切换含税不含税复选框
function taxChange(e){
    $("#materialTable tbody tr").each(function() {
       countProcess($(this))
    })
}
</script>
efo;
		//返回
		return $this->tab($data);
	}

	public function editEdit()
	{
		$id              = $this->post('id') ?: self::getId();
		$mxIdArr         = $this->post('mxId') ?: [];
		$materialIdArr   = $this->post('materialId');
		$numArr          = $this->post('num');
		$priceArr        = $this->post('price');
		$mxTextArr       = $this->post('mxText');
		$unitArr         = $this->post('unitDetail');
		$taxRateArr      = $this->post('rate');
		$moneyWithTaxArr = $this->post('moneyWithTax');
		$field           = [
			'description' => $this->post('description'),
			'text'        => $this->post('text'),
			'opId'        => $this->post('opId'),
			'khid'        => $this->post('khid'),
			'recordDate'  => $this->post('recordDate'),
			'startDate'   => $this->post('startDate'),
			'endDate'     => $this->post('endDate'),
			'updateTime'  => $this->time,
		];
		$kehu  = query('kehu', "khid = '$field[khid]'");
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('quotations.editEdit.power');
		} elseif (!empty($info['id']) && $info['state'] == '已确认') {
			$json['warn'] = L('quotations.editEdit.stateError');
		} else {
			$this->startTrans();
			$isPass           = true;//事务通过标志
			$field['manager'] = $kehu['manager'];
			if (!$info['id']) {
				$userNo       = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'XSBJ' . date('Ymd', strtotime($field['recordDate'])),
					'table'  => self::table,
					'field'  => 'orderNo',
					'where'  => '',
				], $field);
				$field        = array_merge($field, [
					'id'      => $id,
					'coid'=>self::$coid,
					'orderNo' => $userNo,
					'state'   => '制单',
					'stid'    => $this->control['stid'],
					'time'    => $this->time,
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}

			//添加或更新报价单明细
			if (is_array($mxIdArr)) {
				foreach ($mxIdArr as $k => $nid) {
					$numArr[$k]   = self::formattingFigure($numArr[$k], 'numPrecision');
					$priceArr[$k] = self::formattingFigure($priceArr[$k], 'pricePrecision');
					//数据格式处理
					$taxRateArr[$k] = floatval($taxRateArr[$k]) / 100;//税率从百分比转为小数
					$result         = saleOrderClass::isTax($numArr[$k], $priceArr[$k], $taxRateArr[$k]);
					if (static::total(array('table' => self::tableMx, 'where' => " and id = '$nid'")) > 0) {
						//更新
						$warn = static::update([
							"table" => self::tableMx,
							"field" => [
								'unit'            => $unitArr[$k],
								'materialId'      => $materialIdArr[$k],
								'num'             => $numArr[$k],
								'price'           => $priceArr[$k],
								'taxMoney'        => $result['taxMoney'],//税额
								'moneyWithOutTax' => $result['money'],//不含税金额
								'money'           => $moneyWithTaxArr[$k],
								'taxRate'         => $taxRateArr[$k],
								'text'            => $mxTextArr[$k],
							],
							"where" => " id = '$nid'",
						]);
					} else {
						//新增
						$warn = static::insert([
							"table" => self::tableMx,
							"field" => [
								'id'              => $nid,
								'coid'=>self::$coid,
								'orderId'         => $id,
								'materialId'      => $materialIdArr[$k],
								'unit'            => $unitArr[$k],
								'num'             => $numArr[$k],
								'price'           => $priceArr[$k],
								'taxMoney'        => $result['taxMoney'],//税额
								'moneyWithOutTax' => $result['money'],//不含税金额
								'money'           => $moneyWithTaxArr[$k],
								'taxRate'         => $taxRateArr[$k],
								'text'            => $mxTextArr[$k],
							],
						]);
					}
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$isPass       = false;
						$json['warn'] = $warn;
						break;
					}
				}
			}

			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
				$money = find(array('table' => self::tableMx, 'where' => "orderId = '$id'", 'sum' => "money"));
				update(array('table' => self::table, 'field' => ['money' => $money], 'where' => "id = '$id'"));
                if ($json['warn'] =='新增成功'){
                    self::insertOperateLog($id,self::title,"新建");
                }
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('quotations.editEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/**
	 * @return bool|string
	 */
	public function addMx()
	{
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 1;
        $data             = [
            'material_type'            => "产品",
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
	}
	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMxEdit()
	{
		$mxIdArr = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = L('quotations.addMxEdit.power');
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$json['warn'] = L('quotations.addMxEdit.noChoice');
		} else {
			$json['html'] = '';
			$tr           = [];
			foreach ($mxIdArr as $mxId) {
				$material              = query('material', "id = '$mxId'");
				$select                = select(array(
				    'name' => 'rate[]',
                    'change' => "countMoney",
                    'title' => L('quotations.addMxEdit.rate'),
                    'option' => explode('，', para('taxRate'))
                ));
				$id                    = self::getId();
				$material['salePrice'] = $material['salePrice'] ? self::formattingFigure($material['salePrice'], 'pricePrecision') : '';
				$tr[]                  = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'materialId[]', 'value' => $material['id'])),
					$material['code'],
                    $material['name'],
                    $material['model'],
					select(array(
					    'name' => 'unitDetail[]',
                        'data' => ['unit' => $material['unit']],
                        'value' => $material['unit'],
                        'option' => machiningOrderClass::unitOption($material['id'])
                    )),
					text(array('name' => 'num[]', 'blur' => "countMoney", 'other' => self::digitalFiltering('numPrecision'))),
					text(array('name' => 'price[]', 'blur' => "countMoney", 'other' => self::digitalFiltering('pricePrecision'), 'value' => self::lostZero($material['salePrice'], 'pricePrecision'))),
					"<span class='rowMoney'></span>",
					$select,
					"<span class='taxMoney'></span>",
					text(array('name' => 'moneyWithTax[]', 'type' => 'text', 'blur' => 'calculatePrice', 'other' => self::digitalFiltering())),
					text(array('name' => 'mxText[]', 'class' => 'text textPrice')),
				];
			}
			$json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
			$json['warn'] = 2;
		}
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = L('quotations.detail.empty');
		} else {
			//菜单
			$data = array(
				"id"    => $info['id'],
				"title" => L('quotations.detail.quotationsDetail'),
			);

			$button = [];
			if ($info['state'] == '制单') {
				if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => L('quotations.detail.sub'),
                        "type" => "弹出层",
                        "cla"  => $this->get('cla'),
                        "fun"  => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
					//按钮
					$button[] = [
						"name"  => L('quotations.detail.edit'),
						"type"  => "顶部页卡",
						"title" => L('quotations.detail.editDetail'),
						"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
					];
				}
				if ($this->power(self::page, "del")) {
					//按钮
					$button[] = [
						"name" => L('quotations.detail.del'),
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'del', "id" => $info['id']],
					];
				}
			}
			if ($this->power(self::page, "cancel") && $info['state'] != '制单') {
				$button[] = [
					"name" => L('quotations.detail.cancel'),
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'cancel', "id" => $info['id']],
				];
			}
			//按钮
			$button[] = [
				"name" => L('quotations.detail.print'),
				"type" => "点击事件",
				"fun"  => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
			];
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name" => '复核',
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
				];
			}
            //操作记录
            $button[] = self::operateLogBut($info['id'],1);

			$kehu        = query('kehu', "khid = '$info[khid]'");
			$opportunity = query('opportunity', "id = '$info[opId]'");

			$tr[]   = ['{l.quotations.edit.code}', '{l.quotations.edit.name}', '{l.quotations.edit.model}', '{l.quotations.edit.unit}', '{l.quotations.edit.num}', '{l.quotations.edit.price}(' . static::$unit . ')', '{l.quotations.edit.money}（' . static::$unit . '）', '{l.quotations.edit.rate}%', '{l.quotations.edit.taxMoney}（' . static::$unit . '）', '{l.quotations.edit.moneyWithTax}（' . static::$unit . '）', '{l.quotations.edit.mxText}'];
			$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
			foreach ($result['array'] as $array) {
				$material = query('material', " id = '$array[materialId]'");
				$tr[]     = [
					$material['code'],
					$material['name'],
					$material['model'],
					$array['unit'],
					self::lostZero($array['num'], 'numPrecision'),
					self::lostZero($array['price'], 'pricePrecision'),
					self::lostZero($array['moneyWithOutTax']),
					($array['taxRate'] * 100) . '%',
					self::formattingFigure($array['taxMoney']),
					self::formattingFigure($array['money']),
					$array['text'],
				];
			}
            $total               = find(array(
                'table' => self::tableMx,
                'field' => "ifnull(sum(num),0) as num,ifnull(sum(money),0) as totalMoney,ifnull(sum(taxMoney),0) as taxMoney,ifnull(sum(moneyWithOutTax),0) as moneyWithOutTax",
                'single' => "orderId = '$info[id]'"
            ));
			$total['num']             = self::formattingFigure($total['num']??0);
			$total['totalMoney']      = self::formattingFigure($total['totalMoney']??0);
			$total['taxMoney']        = self::formattingFigure($total['taxMoney']??0);
			$total['moneyWithOutTax'] = self::formattingFigure($total['moneyWithOutTax']??0);
            $total_tr = [
                    4=>$total['num'],
                    6=>$total['moneyWithOutTax'],
                    8=>$total['taxMoney'],
                    9=>$total['totalMoney'],
            ];
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow(array(
				"详细信息" => array(
					array(
						L('quotations.edit.description')   => $info['description'],
                        L('quotations.edit.opId') => $opportunity['name'],
                        L('quotations.edit.khid')         => $kehu['companyName'],
                        L('quotations.detail.manager')   => self::findStaff($info['manager']),
					),
					array(
                        L('quotations.edit.recordDate') => $info['recordDate'],
                        L('quotations.edit.startDate') => self::null($info['startDate']),
                        L('quotations.edit.endDate') => self::null($info['endDate']),
					),
                    array(
                        L('quotations.edit.mxText')     => pre($info['text']),
                    ),
					array(
                        L('quotations.detail.orderNo') => $info['orderNo'],
                        L('quotations.detail.stid')   => self::findStaff($info['stid']),
                        L('quotations.detail.state')     => $info['state']
					),
				),
			));
            $data['html'] .= $this->detailList([
                'title' => L('quotations.edit.quotationsMx'),
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 撤回
	 */
	public function cancelEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state'       => '制单',
			'checkId'     => '',
			'confirmTime' => '',
		];
		if (!$this->power(self::page, 'cancel')) {
			$json['warn'] = L('quotations.cancelEdit.power');
		} elseif (empty($info['id'])) {
			$json['warn'] = L('quotations.cancelEdit.empty');
		} elseif ($info['state'] == '制单') {
			$json['warn'] = '此报价单是制单状态，无需撤回';
		} elseif (static::total(array('table' => 'sales_contract_detail', "where" => "sourceId = '$info[id]'")) > 0) {
			$json['warn'] = L('quotations.cancelEdit.associated');
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                self::insertOperateLog($info['id'],self::title,"撤回");
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('quotations.cancelEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = L('quotations.cancelEdit.success');
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 确认
	 */
	public function confirmEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state'       => '已确认',
			'checkId'     => self::$stid,
			'confirmTime' => $this->time,
		];
		if (!$this->power(self::page, 'confirm')) {
			$json['warn'] = L('quotations.confirmEdit.power');
		} elseif (empty($info['id'])) {
			$json['warn'] = L('quotations.confirmEdit.empty');
		} elseif ($info['state'] != '待确认') {
			$json['warn'] = L('quotations.confirmEdit.stateError');
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'],self::title,"提交、复核");
                }else{
                    self::insertOperateLog($info['id'],self::title,"复核");
                }
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('quotations.confirmEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
	public function dataValidation($info): string|bool
    {
        $annotation      = [
            'startDate'   => L('quotations.editEdit.startDate'),
            'description' => L('quotations.editEdit.description'),
            'recordDate'  => L('quotations.editEdit.recordDate'),
            'khid'        => L('quotations.editEdit.khid'),
        ];
        $rules           = [
            'startDate'   => 'required',
            'description' => 'required',
            'recordDate'  => 'required',
            'khid'        => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($info, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];  // 多个规则提示最前面一条
        }
        $result = find(array('table' => self::tableMx, 'field' => 'id,num,price', 'where' => "orderId = '$info[id]' order by list"));
        if(count($result['array']) == 0){
            return "请完善报价明细";
        }
        if(static::is_null_array(array_column($result['array'],'price'))){
            return "报价明细中【单价】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'num'),false)){
            return "报价明细中【数量】不能为空，且必须大于0";
        }

        return true;
    }

	/**
	 * 提交
	 */
	public function commitEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state' => '待确认',
		];
		//提交前数据验证
        $json['warn'] = $this->dataValidation($info);
		if($json['warn'] !== true){
            goto resp;
        }
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = L('quotations.commitEdit.power');
		} elseif (empty($info['id'])) {
			$json['warn'] = L('quotations.commitEdit.empty');
		} elseif ($info['state'] != '制单') {
			$json['warn'] = L('quotations.commitEdit.stateError');
		} else {
            $this->startTrans();
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
			    // 单据是否需要复核
			    if(!in_array(self::page,self::$publicSettings['documentReview'])){
                    $resultJson = $this->confirmEdit();
                    $json = json_decode($resultJson,true);
                    if ($json['warn'] != 2){
                        $this->rollback();
                        goto resp;
                    }
                }else {
                    self::insertOperateLog($info['id'],self::title,"提交");
                }
                $this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('quotations.commitEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			} else {
                $this->rollback();
            }
		}
		resp:
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = $word = false; // 需要密码
		$form = $power = '';
		switch ($act) {
			case 'confirm':
				$act      = 'confirm';
				$msg      = L('quotations.operate.confirm');
				$title    = L('quotations.operate.confirmTitle');
				$function = 'confirmEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'commit':
				$act      = 'edit';
				$msg      = L('quotations.operate.commit');
				$title    = L('quotations.operate.commitTitle');
				$function = 'commitEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'cancel':
				$act      = 'cancel';
				$msg      = L('quotations.operate.cancel');
				$title    = L('quotations.operate.cancelTitle');
				$function = 'cancelEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			default:
				$act      = 'del';
				$msg      = L('quotations.operate.del');
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('quotations.operate.warn'));
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = L('quotations.delete.power');
		} elseif (empty($array)) {
			$json['warn'] = L('quotations.delete.noChoice');
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['state'] == '已确认') {
					$warn =  L('quotations.delete.fail');
				} else {
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
					//返回
					$warn =  L('quotations.delete.success');
					$x++;
				}
				$text .= str_replace(['{{id}}'], [$info['id']], L('quotations.delete.text')) . $warn . "。<br>";
			}
			//添加日志
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('quotations.delete.log')) . "<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('quotations.delete.warn'));
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}


	/**
	 * 批量打印
	 *
	 * @return string
	 */
	public function batchPrint(): string
	{
		$lists = $this->get('lists');
		if (empty($lists)) {
			exit(L('quotations.batchPrint.error'));
		} else {
			$listId = base64_decode($lists, true);
			$array  = explode(',', $listId);
			$data   = [];
			foreach ($array as $id) {
				$data[] = static::printPage($id, false);
			}
			return (new printTemplateClass())->start(self::page, $data);
		}
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage($param = '', $isReturn = true): string|array
	{
		$id                  = $param ?: $this->get('id');
		$info                = query(self::table, " id = '$id'");
		$info['companyName'] = ''; //公司名称//公司名称
		$info['title']       = L('quotations.printPage.quotations');
		$info['printTime']   = $this->time;
		$info['stid']        = self::findStaff($info['stid']);
		$info['checkId']     = self::findStaff($info['checkId']);
		$info['khid']        = query('kehu', "khid = '$info[khid]'")['companyName'];
		$info['manager']     = self::findStaff($info['manager']);
		$detail              = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
		$items               = [];
		$x                   = 1;
		$totalNum            = $totalMoney = $totalTax = $total = 0;
		foreach ($detail as $array) {
			$material = query('material', "id = '$array[materialId]'");
			$tax      = ($array['taxRate'] * 100) . '%';
			$taxMoney = self::formattingFigure($array['money'] * $array['taxRate'], 'amount');
			$items[]  = [
				'no'           => $x,
				'materialCode' => $material['code'],
				'materialName' => $material['name'],
				'model'        => $material['model'],
				'unit'         => $material['unit'],
				'num'          => self::lostZero($array['num'], 'numPrecision'),
				'price'        => self::lostZero($array['price'], 'pricePrecision'),
				'money'        => self::lostZero($array['money'], 'amount'),
				'rate'         => $tax,
				'taxMoney'     => $taxMoney,
				'total'        => self::formattingFigure($array['money'] + $taxMoney, 'amount'),
				'text'         => $array['text'],
			];
			$x++;
			$totalNum   += $array['num'];
			$totalMoney += $array['money'];
			$totalTax   += $taxMoney;
			$total      += ($array['money'] + $taxMoney);
		}
		$append         = [
			'no'       => L('quotations.printPage.total'),
			'num'      => $totalNum,
			'money'    => $totalMoney,
			'taxMoney' => $totalTax,
			'total'    => $total,
		];
		$items[]        = $append;
		$info['detail'] = $items;
		if ($isReturn) {
			return (new printTemplateClass())->start(self::page, $info);
		} else {
			return $info;
		}
	}

}

